package com.outfood.consumer.hander;

import com.alibaba.fastjson.JSON;
import com.outfood.config.WxConfig;
import com.outfood.domain.RechargeRecord;
import com.outfood.domain.Store;
import com.outfood.domain.User;
import com.outfood.service.IRechargeRecordService;
import com.outfood.service.IStoreService;
import com.outfood.service.IUserService;
import com.outfood.service.impl.MeiTuanOperateServiceImpl;
import com.outfood.service.impl.StoreServiceImpl;
import com.outfood.utils.profitshare.ShareUtil;
import com.rys.common.enums.SearchTypeEnum;
import com.rys.common.utils.DateUtils;
import com.rys.common.utils.Search;
import com.tps.open.mq.MqService;
import com.tps.open.mq.enums.QueueEnums;
import com.tps.open.mq.model.MessageBody;
import com.tps.open.weixin.dto.TemplateDTO;
import com.tps.open.weixin.dto.TemplateValue;
import com.tps.open.weixin.vo.XcxPayNotifyInfoVO;
import lombok.extern.log4j.Log4j2;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

@Component
@Log4j2
public class XcxPayNotifyCusmerHander implements  ComsumerHander{

    @Resource
    IStoreService storeService;
    @Resource
    IRechargeRecordService rechargeRecordService;

    @Resource
    ShareUtil shareUtil;


    @Override
    public void toHandle(MessageBody messageBody) {
        String body = messageBody.getBody();
        log.info("微信支付回调内容为{}",body);

        XcxPayNotifyInfoVO xcxPayNotifyInfoVO = JSON.parseObject(body, XcxPayNotifyInfoVO.class);

        RechargeRecord rechargeRecord = rechargeRecordService.getList(new Search().add("orderNo", SearchTypeEnum.EqualTo, xcxPayNotifyInfoVO.getOut_trade_no())).get(0);
        User user = userService.get(rechargeRecord.getUserId());
        log.info("该用户的推荐人ID为===================================================="+user.getReferenceId());
        if(user.getReferenceId() != null){
            log.info("符合条件开始分账====================================================");
            //开始进行分账
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(20000L);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        shareUtil.share(xcxPayNotifyInfoVO,user.getReferenceId());
                    }
                }).start();

        }
        rechargeRecord.setLoanNo(xcxPayNotifyInfoVO.getTransaction_id());
        rechargeRecord.setStatus("1");
        rechargeRecordService.update(rechargeRecord.getId(),rechargeRecord,"callback");
        Store store = storeService.get(rechargeRecord.getStoreId());
        Integer renewDay = Integer.valueOf(rechargeRecord.getMonth())*30;
        if("2".equals(store.getStoreStatus())){
            store.setExpireTime(DateUtils.addDays(new Date(),renewDay));
            store.setStoreStatus("1");
        }else{
            store.setExpireTime(DateUtils.addDays(store.getExpireTime(),renewDay));
        }

        storeService.update(store.getId(),store,"callback");
        remind(store,xcxPayNotifyInfoVO.getCash_fee());


    }

    @Resource
    MeiTuanOperateServiceImpl meiTuanOperateService;

    @Resource
    IUserService userService;

    @Resource
    WxConfig wxConfig;

    @Reference
    MqService mqService;

    public void remind(Store store,String amount){
        MessageBody messageBody = new MessageBody();
        List<String> openIdList = meiTuanOperateService.getOpenIdList(store.getId());
        openIdList.forEach(openId ->{
            messageBody.setHandlerBeanName("templateComsumerHandler");
            TemplateDTO templateDTO = new TemplateDTO();
            templateDTO.setTemplate_id("2Yxf7H4Ff2mG81aVj6d0wKE24uoxU6fe2xIFpwtv4vE");
            templateDTO.setTouser(openId);
            Map<String, TemplateValue> data = new HashMap<>();
            data.put("thing1", new TemplateValue(store.getStoreName().length() > 20?store.getStoreName().substring(0,17)+"...":store.getStoreName()));
            data.put("thing6", new TemplateValue("一个月"));
            data.put("amount4", new TemplateValue(amount+""));
            data.put("time7", new TemplateValue(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm",store.getExpireTime())));
            templateDTO.setPage("/pages/index/index");
            templateDTO.setData(data);
            templateDTO.setAppid(wxConfig.getWxAppid());
            templateDTO.setSecret(wxConfig.getWxSecret());
            messageBody.setBody(JSON.toJSONString(templateDTO));
            mqService.send(messageBody, QueueEnums.WEIXIN_ADMIN);
        });

    }
}
